package miniologic

import (
	"context"

	"go-zero-admin/apps/frame/storage/cmd/rpc/internal/svc"
	"go-zero-admin/apps/frame/storage/cmd/rpc/stopb"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/minio/minio-go/v7"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DelFileAtMinioLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelFileAtMinioLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelFileAtMinioLogic {
	return &DelFileAtMinioLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DelFileAtMinioLogic) DelFileAtMinio(in *stopb.DelFileAtMinioReq) (*stopb.DelFileAtMinioResp, error) {
	// 检验参数
	if err := l.valid(in); err != nil {
		return nil, err
	}

	// 删除
	err := l.svcCtx.MinioClient.RemoveObject(l.ctx, in.GetBucketName(), in.GetObjectName(), minio.RemoveObjectOptions{})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除失败"),
			tool.GetErrMsgFormat("delete minio file"), err, in)
	}

	return &stopb.DelFileAtMinioResp{}, nil
}

// 校验参数
func (l *DelFileAtMinioLogic) valid(in *stopb.DelFileAtMinioReq) error {
	bucketName := in.GetBucketName()
	if bucketName == "" {
		return errors.Wrapf(xerr.NewErrMsg("删除失败：桶名不存在"),
			tool.GetErrMsgFormat("delete minio file"), "bucket name is not existed", in)
	}

	objectName := in.GetObjectName()
	if objectName == "" {
		return errors.Wrapf(xerr.NewErrMsg("删除失败：文件名不存在"),
			tool.GetErrMsgFormat("delete minio file"), "file name is not existed", in)
	}

	return nil
}
